﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OnlineMealOrdering.Common
{
    /// <summary>
    /// 上传文件暂存对象
    /// </summary>
    public class FileSavingInfo
    {
        public Guid FileId { get; set; }

        /// <summary>
        /// for example:abc.jpg
        /// </summary>
        public string RawFileName { get; set; }

        /// <summary>
        /// for example: .jpg
        /// </summary>
        public string FileType { get; set; }

        /// <summary>
        /// 相对路径(不带文件名)
        /// </summary>
        public string RawFileAppRelativePath { get; set; }

        /// <summary>
        /// 绝对路径(不带文件名)
        /// </summary>
        public string RawFileAbsolutePath { get; set; }

        /// <summary>
        /// 缩略图的路径如:adsfsd-asdfsd-sdfsdf(不包含扩展名)
        /// </summary>
        public string ThumbnailFileName { get; set; }

        /// <summary>
        /// 缩略图相对路径
        /// </summary>
        public string ThumbnailAppRelativePath { get; set; }

        /// <summary>
        /// 缩略图绝对路径
        /// </summary>
        public string ThumbnailAbsolutePath { get; set; }

        public long RawFileSize { get; set; }

    }

    public class FileHelper
    {
        #region 产品上传图片常量

        static Dictionary<int, string> saveType;

        public static Dictionary<int, string> SaveType
        {
            get
            {
                if (saveType == null)
                {
                    saveType = new Dictionary<int, string>();
                    var names = Enum.GetNames(typeof(UploadFileSaveType));
                    names.ToList().ForEach(a =>
                    {
                        saveType.Add((int)Enum.Parse(typeof(UploadFileSaveType), a), a);
                    });
                }
                return saveType;
            }
        }

        private const string _RawImagePath = @"Images\WebSiteImage";

        private const string _ThumbnailPath = @"Images\WebSiteImage\Thumbnail";

        private const int _ThumbnailWidth = 70;

        private const int _ThumbnailHeight = 70;

        #endregion

        #region 文件操作

        public static void DeleteFile(string filePath)
        {
            filePath = filePath.Replace('/', '\\');
            if (FileExists(filePath))
            {
                File.Delete(filePath);
            }
        }

        public static void DeleteFiles(string[] paths)
        {
            if (paths.Count() > 0)
                paths.ToList().ForEach(a => { DeleteFile(a); });
        }

        public static bool FileExists(string filePath)
        {
            filePath = filePath.Replace('/', '\\');
            return File.Exists(filePath);
        }

        public static string CreateDirectory(string directoryPath)
        {
            directoryPath = directoryPath.Replace('/', '\\');

            var path = Path.GetFullPath(directoryPath);
            if (Directory.Exists(directoryPath))
            {
                return directoryPath;
            }
            try
            {
                Directory.CreateDirectory(directoryPath);
            }
            catch (Exception e)
            {

            }
            return directoryPath;
        }

        #endregion

        

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="filepath">要保存的路径 不带文件名称(据对路径)</param>
        /// <param name="filename">原文件名</param>
        /// <param name="inputStream">图片的数据</param>        
        /// <param name="thumbnailPath">生成缩略图的路径</param>
        /// <param name="thumbnailWidth">缩略图宽</param>
        /// <param name="thumbnailHeight">缩略图高</param>
        /// <returns>返回新的文件名称</returns>
        static string SaveImage(string filepath, string filename, Stream inputStream, string thumbnailPath = null, int thumbnailWidth = 70, int thumbnailHeight = 70)
        {
            var fileName = Guid.NewGuid() + Path.GetExtension(filename);
            var filePath = Path.Combine(filepath, fileName);
            using (var image = Image.FromStream(inputStream))
            {
                CreateDirectory(filepath);

                image.Save(filePath);
            }
            if (thumbnailPath != null)
            {
                //缩略图和原图的文件名字一样
                MakeThumbnail(filePath, Path.Combine(thumbnailPath, Path.GetFileName(filePath)), thumbnailWidth, thumbnailHeight);
            }
            return fileName;
        }

        #region 产品图片处理

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="root">虚拟目录根目录的物理路径</param>
        /// <param name="imagePath">原图路径</param>
        /// <param name="ThumbnailPath">缩略图路径</param>
        public static void DeleteImages(string root, string imagePath, string ThumbnailPath = null)
        {
            DeleteFile(Path.Combine(root, imagePath));
            if (ThumbnailPath == null) return;
            DeleteFile(Path.Combine(root, ThumbnailPath));
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="rawFilePath">原图绝对路径</param>
        /// <param name="thumbFilePath">缩略图绝对路径</param>
        public static void DeleteImageWithThumb(string rawFilePath, string thumbFilePath)
        {
            DeleteFile(rawFilePath);
            DeleteFile(thumbFilePath);
        }


        /// <summary>
        /// 保存原图并且生成缩略图 
        /// </summary>
        /// <param name="root"></param>
        /// <param name="rawFileName"></param>
        /// <param name="inputStream"></param>
        /// <param name="isGenerateTbumbnali"></param>
        /// <param name="tbumbnaliImagePath"></param>
        /// <returns></returns>
        public static FileSavingInfo SaveImage(string root, string rawFileName, Stream inputStream, bool isGenerateTbumbnali, int type = 0)
        {
            var timeFolder = DateTime.Now.ToString("yyyyMM");
            var fileModel = new FileSavingInfo();
            //图片保存的绝对目录
            fileModel.RawFileAbsolutePath = Path.Combine(root, _RawImagePath, timeFolder);
            //图片保存的相对目录
            fileModel.RawFileAppRelativePath = Path.Combine(_RawImagePath, timeFolder);
            fileModel.RawFileSize = inputStream.Length;

            if (isGenerateTbumbnali)
            {
                //缩略图保存的绝对路径
                fileModel.ThumbnailAbsolutePath = Path.Combine(root, _ThumbnailPath, timeFolder);
            }

            string tmpGuid = SaveImage(fileModel.RawFileAbsolutePath, rawFileName, inputStream, fileModel.ThumbnailAbsolutePath, _ThumbnailWidth, _ThumbnailHeight);

            fileModel.RawFileName = Path.GetFileName(rawFileName);

            

            fileModel.FileId = new Guid(Path.GetFileNameWithoutExtension(tmpGuid));

            fileModel.ThumbnailFileName = Path.GetFileNameWithoutExtension(tmpGuid);
            fileModel.ThumbnailAppRelativePath = isGenerateTbumbnali ? Path.Combine(_ThumbnailPath, timeFolder) : "";

            fileModel.FileType = Path.GetExtension(fileModel.RawFileName);
            return fileModel;

        }

        /// <summary>    
        /// 生成缩略图    
        /// </summary>    
        /// <param name="originalImagePath">源图路径（物理路径）</param>    
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>    
        /// <param name="m_Width">缩略图宽度</param>    
        /// <param name="m_Height">缩略图高度</param>      
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int m_Width, int m_Height)
        {
            CreateDirectory(Path.GetDirectoryName(thumbnailPath));
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
            int towidth = 0;
            int toheight = 0;
            if (originalImage.Width <= m_Width && originalImage.Height <= m_Height)
            {
                towidth = originalImage.Width;
                toheight = originalImage.Height;
            }
            else
            {
                var temp = Convert.ToDouble(m_Width) / Convert.ToDouble(m_Height);
                var temp1 = Convert.ToDouble(originalImage.Width) / Convert.ToDouble(originalImage.Height);
                if (temp1 >= temp)
                {
                    towidth = m_Width;
                    toheight = Convert.ToInt32(Convert.ToDouble(m_Width) / temp1);
                }
                else
                {
                    towidth = Convert.ToInt32(Convert.ToDouble(m_Height) * temp1);
                    toheight = m_Height;
                }
            }
            int x = 0;//左上角的x坐标    
            int y = 0;//左上角的y坐标    
            //新建一个bmp图片    
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板    
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法    
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度    
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充    
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分    
            g.DrawImage(originalImage, x, y, towidth, toheight);
            try
            {
                //以jpg格式保存缩略图    
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        #endregion
    }
}
